package com.linfeng.api.aspect;

import com.linfeng.api.service.LogService;
import com.linfeng.api.util.RequestHolder;
import com.linfeng.api.util.StringUtils;
import com.linfeng.api.util.ThrowableUtil;
import com.linfeng.api.util.thread.LocalUser;
import com.linfeng.common.domain.system.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author linfeng
 * @date 2021/1/12 19:51
 */
@Component
@Aspect
@Slf4j
public class AppLogAspect {

    @Autowired
    private LogService logService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();


    @Pointcut("@annotation(com.linfeng.api.annotation.AppLog)")
    public void logPointCut(){
        // 配置织入点
    }

    @Around("logPointCut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        Log log = new Log("INFO",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        logService.saveApp(getUsername(),
                StringUtils.getIp(RequestHolder.getHttpServletRequest()),
                joinPoint,
                log,getUid());
        return result;
    }
    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointCut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        Log log = new Log("ERROR",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes());
        logService.saveApp(getUsername(),
                StringUtils.getIp(RequestHolder.getHttpServletRequest()),
                (ProceedingJoinPoint)joinPoint, log,getUid());
    }

    private String getUsername() {
        try {
            return LocalUser.getUser().getUsername();
        }catch (Exception e){
            return "";
        }
    }

    private Long getUid(){
        try {
            return LocalUser.getUser().getUid();
        }catch (Exception e){
            return 0L;
        }
    }

}
